import { message } from 'antd';
import type { CrudConfig } from '../components/PageTemplate/types';
import { request } from '../utils/request';

export class CrudService<T = any> {
  private config: CrudConfig;

  constructor(config: CrudConfig) {
    this.config = {
      methods: {
        list: 'POST',
        create: 'POST',
        update: 'POST',
        delete: 'POST',
        detail: 'POST',
      },
      ...config,
    };
  }

  // 查询列表
  async list(params: Record<string, any> = {}): Promise<{ data: T[]; total?: number; success?: boolean }> {
    try {
      const endpoint = this.config.endpoints.list;
      if (!endpoint) {
        throw new Error('List endpoint not configured');
      }

      // 参数转换
      const transformedParams = this.config.transformRequest?.list ? this.config.transformRequest.list(params) : params;

      const response = await request(endpoint, {
        method: this.config.methods?.list || 'GET',
        params: this.config.methods?.list === 'GET' ? transformedParams : undefined,
        data: this.config.methods?.list === 'POST' ? transformedParams : undefined,
      });

      // 响应转换
      const result = this.config.transformResponse?.list
        ? this.config.transformResponse.list(response)
        : { data: response.data || response, total: response.total };

      return {
        success: true,
        ...result,
      };
    } catch (error) {
      this.handleError(error, 'list');
      throw error;
    }
  }

  // 新增记录
  async create(data: Partial<T>): Promise<T> {
    try {
      const endpoint = this.config.endpoints.create;
      if (!endpoint) {
        throw new Error('Create endpoint not configured');
      }

      // 前置回调
      if (this.config.callbacks?.beforeCreate) {
        data = await this.config.callbacks.beforeCreate(data);
      }

      // 参数转换
      const transformedData = this.config.transformRequest?.create ? this.config.transformRequest.create(data) : data;

      const response = await request(endpoint, {
        method: this.config.methods?.create || 'POST',
        data: transformedData,
      });

      // 响应转换
      const result = this.config.transformResponse?.create
        ? this.config.transformResponse.create(response)
        : response.data || response;

      // 后置回调
      if (this.config.callbacks?.afterCreate) {
        await this.config.callbacks.afterCreate(result, data);
      }

      message.success('创建成功');
      return result;
    } catch (error) {
      this.handleError(error, 'create');
      throw error;
    }
  }

  // 更新记录
  async update(id: any, data: Partial<T>): Promise<T> {
    try {
      const endpoint = this.config.endpoints.update;
      if (!endpoint) {
        throw new Error('Update endpoint not configured');
      }

      // 前置回调
      if (this.config.callbacks?.beforeUpdate) {
        data = await this.config.callbacks.beforeUpdate({ id, ...data });
      }

      // 参数转换
      const transformedData = this.config.transformRequest?.update ? this.config.transformRequest.update(data) : data;

      const url = endpoint.includes(':id') ? endpoint.replace(':id', String(id)) : endpoint;

      const response = await request(url, {
        method: this.config.methods?.update || 'PUT',
        data: transformedData,
      });

      // 响应转换
      const result = this.config.transformResponse?.update
        ? this.config.transformResponse.update(response)
        : response.data || response;

      // 后置回调
      if (this.config.callbacks?.afterUpdate) {
        await this.config.callbacks.afterUpdate(result, data);
      }

      message.success('更新成功');
      return result;
    } catch (error) {
      this.handleError(error, 'update');
      throw error;
    }
  }

  // 删除记录
  async delete(id: any): Promise<boolean> {
    try {
      const endpoint = this.config.endpoints.delete;
      if (!endpoint) {
        throw new Error('Delete endpoint not configured');
      }

      // 前置回调
      if (this.config.callbacks?.beforeDelete) {
        const shouldContinue = await this.config.callbacks.beforeDelete(id);
        if (!shouldContinue) {
          return false;
        }
      }

      // 参数转换
      const transformedParams = this.config.transformRequest?.delete ? this.config.transformRequest.delete(id) : { id };

      const url = endpoint.includes(':id') ? endpoint.replace(':id', String(id)) : endpoint;

      const response = await request(url, {
        method: this.config.methods?.delete || 'DELETE',
        data: transformedParams,
      });

      // 后置回调
      if (this.config.callbacks?.afterDelete) {
        await this.config.callbacks.afterDelete(response, id);
      }

      message.success('删除成功');
      return true;
    } catch (error) {
      this.handleError(error, 'delete');
      throw error;
    }
  }

  // 获取详情
  async detail(id: any): Promise<T> {
    try {
      const endpoint = this.config.endpoints.detail;
      if (!endpoint) {
        // endpoint 未配置时，抛出特殊错误，但不显示错误消息（这是配置问题，不是运行时错误）
        const error = new Error('Detail endpoint not configured');
        // 标记这个错误，避免显示错误消息
        (error as any).skipErrorHandler = true;
        throw error;
      }

      const url = endpoint.includes(':id') ? endpoint.replace(':id', String(id)) : endpoint;

      const response = await request(url, {
        method: this.config.methods?.detail || 'GET',
      });

      // 响应转换
      const result = this.config.transformResponse?.detail
        ? this.config.transformResponse.detail(response)
        : response.data || response;

      return result;
    } catch (error: any) {
      // 如果错误标记了 skipErrorHandler，不显示错误消息
      if (!error?.skipErrorHandler) {
        this.handleError(error, 'detail');
      }
      throw error;
    }
  }

  // 批量删除
  async batchDelete(ids: any[]): Promise<boolean> {
    try {
      const endpoint = this.config.endpoints.delete;
      if (!endpoint) {
        throw new Error('Delete endpoint not configured');
      }

      const response = await request(`${endpoint}/batch`, {
        method: 'DELETE',
        data: { ids },
      });

      message.success(`成功删除 ${ids.length} 条记录`);
      return true;
    } catch (error) {
      this.handleError(error, 'batchDelete');
      throw error;
    }
  }

  // 错误处理
  private handleError(error: any, operation: string) {
    console.error(`CRUD ${operation} operation failed:`, error);

    if (this.config.callbacks?.onError) {
      this.config.callbacks.onError(error, operation);
    } else {
      // 默认错误处理
      const errorMessage = error?.response?.data?.message || error?.message || '操作失败';
      message.error(errorMessage);
    }
  }
}

// 创建CRUD服务实例的工厂函数
export function createCrudService<T = any>(config: CrudConfig): CrudService<T> {
  return new CrudService<T>(config);
}

// 常用的CRUD配置预设
export const commonCrudConfigs = {
  // 标准REST API配置
  restful: (baseUrl: string): CrudConfig => ({
    endpoints: {
      list: baseUrl,
      create: baseUrl,
      update: `${baseUrl}/:id`,
      delete: `${baseUrl}/:id`,
      detail: `${baseUrl}/:id`,
    },
    methods: {
      list: 'POST',
      create: 'POST',
      update: 'PUT',
      delete: 'POST',
      detail: 'POST',
    },
  }),

  // 自定义查询方式（POST查询）
  postQuery: (baseUrl: string): CrudConfig => ({
    endpoints: {
      list: `${baseUrl}/query`,
      create: baseUrl,
      update: `${baseUrl}/:id`,
      delete: `${baseUrl}/:id`,
      detail: `${baseUrl}/:id`,
    },
    methods: {
      list: 'POST',
      create: 'POST',
      update: 'POST',
      delete: 'POST',
      detail: 'POST',
    },
  }),
};
